import { EditorInputEvent, EditorOutputEvent } from "../com/editor-struct";
import { DataBus } from "../core/utils/DataBus";
import { AppComUtils } from "./com";

export const vscode = acquireVsCodeApi();

export class SgsEditor {
    
    static callEnvMethod<T>(outType: EditorOutputEvent, data?: any): Promise<T> {
        return new Promise((resolve, reject) => {
            const handler = (event: MessageEvent) => {
                const { type } = event.data
                if (outType + '-res' === type) {
                    window.removeEventListener('message', handler)
                    resolve(event.data.data)
                }
            }
            if (import.meta.env.MODE === 'vscode') {
                vscode.postMessage({ type: outType, data });
            } else {
                window.dispatchEvent(new CustomEvent(outType, { detail: data }));
            }
            window.addEventListener('message', handler)
            setTimeout(() => {
                window.removeEventListener('message', handler)
                reject('timeout')
            }, 1000 * 5)
        })
    }

    static saveState(key: string, value: any) {
        const state = vscode.getState() || {}
        state[key] = value
        vscode.setState(state)
    }
    static async init() {
        try {
            SgsEditor.callEnvMethod(EditorOutputEvent.EDITOR_READY, {})
            const info: any = await SgsEditor.callEnvMethod(EditorOutputEvent.ENV_INFO, {})
            AppComUtils.basePath = info.path
            SgsEditor.saveState('content', info.content)
        } catch (error) {
            
            console.error(error)
        }
        window.addEventListener('message', SgsEditor.messageHandler);
    }
    static checkVsState() {
        const previousState = vscode.getState();
        if (previousState) {
            DataBus.ui?.setContent(previousState.content)
        }
    }
    static messageHandler(event: MessageEvent) {
        const { type, data } = event.data
        switch (type) {
            case EditorInputEvent.SET_CONTENT:
                DataBus.ui?.setContent(data.content)
                SgsEditor.saveState('content', data.content)
                break
            case EditorOutputEvent.EXECUTE_CODE + '-res':
                DataBus.ui?.onExecuteDone()
                break
            case EditorInputEvent.NEW_DOC + '-res':
                DataBus.ui?.newDocument()

                break
            case EditorInputEvent.NEW_DOC:
                DataBus.ui?.newDocument()
                break
            case EditorInputEvent.COMPILE_CODE + '-res':
                DataBus.ui?.exportScript()
                break
            case EditorOutputEvent.EXECUTE_CODE:
                DataBus.ui?.runScript()
                break
            case EditorInputEvent.NODE_SELECTOR:
                DataBus.ui?.openNodeSelector()
                break
        }
    }
}